39A - C++ Calculations - CodeForces Solution


expression parsing greedy *2000

Please click on ads to support us..

Python Code:

from typing import List, Tuple, Optional
from collections import deque, Counter
from queue import PriorityQueue
import math
from functools import lru_cache
import random
import copy
import sys
sys.setrecursionlimit(9999)


MOD = 10**9 + 7



init_a = int(input())
s = input()

n = len(s)
i = 0

ss = ""
while i < n:
    if i+2 <= n-1 and (s[i:i+3] == 'a++' or s[i:i+3] == '++a'):
        ss += "X" if s[i:i+3] == 'a++' else 'Y'
        i += 3
    else:
        ss += s[i]
        i += 1

if ss[0] != '-':
    ss = '+' + ss

arr = []
f = []
n = len(ss)
i = 0
while i < n:
    j = i
    while j+1 < n and (ss[j+1] != 'X' and ss[j+1] != 'Y'):
        j += 1

    if ss[j] == '*':
        v = int(ss[i: j])
        arr.append((v, ss[j+1]))
    else:
        if ss[i] == '-':
            arr.append((-1, ss[j+1]))
        else:
            arr.append((1, ss[j+1]))

    i = j+2


arr.sort()

a = init_a
tot = 0
for v, ch in arr:
    if ch == 'Y':
        a += 1

    tot += a * v

    if ch == 'X':
        a += 1


print(tot)


Comments

Submit
0 Comments
More Questions

1701A - Grass Field
489C - Given Length and Sum of Digits
886B - Vlad and Cafes
915A - Garden
356A - Knight Tournament
1330A - Dreamoon and Ranking Collection
1692B - All Distinct
1156C - Match Points
1675A - Food for Animals
1328C - Ternary XOR
1689A - Lex String
1708B - Difference of GCDs
863A - Quasi-palindrome
1478A - Nezzar and Colorful Balls
1581B - Diameter of Graph
404A - Valera and X
908A - New Year and Counting Cards
146A - Lucky Ticket
1594C - Make Them Equal
1676A - Lucky
1700B - Palindromic Numbers
702C - Cellular Network
1672C - Unequal Array
1706C - Qpwoeirut And The City
1697A - Parkway Walk
1505B - DMCA
478B - Random Teams
1705C - Mark and His Unfinished Essay
1401C - Mere Array
1613B - Absent Remainder